package flyshoes.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import flyshoes.mybatis.entity.*;
import flyshoes.mybatis.mapper.CategoryMapper;
import flyshoes.mybatis.mapper.ProductMapper;
import flyshoes.mybatis.service.serviceImpl.*;
import flyshoes.utils.JwtUtil;
import flyshoes.utils.Md5Util;
import lombok.RequiredArgsConstructor;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class AdministerServiceImpl {
    private final ProductServiceImpl productService;
    private final OrderServiceImpl orderService;
    private final UserdetailinfoServiceImpl detailInfoService;
    private final ShippinginformationServiceImpl shippingInformationService;
    private final flyshoes.mybatis.service.serviceImpl.AdminServiceImpl adminService;
    private final RedisTemplate redisTemplate;
    private final CategoryMapper categoryMapper;
    private final ProductMapper productMapper;
    //private final Category category;

    @Transactional
    public Result addProduct(Product product){  //添加或更新商品
        //product.setCategoryId(getCategoryIdByName(category.getCategoryName()));
        boolean b = productService.saveOrUpdate(product);
        if (!b){
            return Result.fail(400,"添加或更新商品失败");
        }
        return Result.success("添加或更新商品成功");
    }
    private String getCellValue(Cell cell){//获取单元格文本值
        switch (cell.getCellType()){
            case NUMERIC:
                return String.valueOf(cell.getNumericCellValue());
            case ERROR:
                return "err:"+cell.getErrorCellValue();
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            default:
                return cell.getStringCellValue();
        }
    }
    @Transactional
    public void uploadProducts(MultipartFile upFile) throws IOException {
        Workbook wb = null;//excel文件
        String fileName = upFile.getOriginalFilename();//原始文件名
        if(fileName.toLowerCase().endsWith("xls")) {
            wb = new HSSFWorkbook(upFile.getInputStream());
        }else if(fileName.toLowerCase().endsWith("xlsx")){
            wb = new XSSFWorkbook(upFile.getInputStream());
        }else {
            throw new RuntimeException("文件格式错误");
        }
        Sheet sheet = wb.getSheetAt(0);//得到第一个表
        int rows = sheet.getPhysicalNumberOfRows();//得到数据的行数
        List<Product> products = new ArrayList<>();
        for(int i=1;i<rows;i++){
            Row row =  sheet.getRow(i);
            Cell cell1 = row.getCell(0);//第一列  鞋名
            Cell cell2 = row.getCell(1);//第2列  描述
            Cell cell3 = row.getCell(2);//第3列  价格
            double price = Double.parseDouble(getCellValue(cell3));
            Cell cell4 = row.getCell(3);//第4列  库存
            double stockQuantity = Double.parseDouble(getCellValue(cell4));
            Cell cell5 = row.getCell(4);//第5列  分类名
            Cell cell6 = row.getCell(5);//第6列  品牌名
            Cell cell7 = row.getCell(6);//第7列  尺码
            Cell cell8 = row.getCell(7);//第8列  图片
            double size = Double.parseDouble(getCellValue(cell7));
            Product product = new Product();
            product.setProductName(getCellValue(cell1));
            product.setProductDescription(getCellValue(cell2));
            product.setPrice((int) price);
            product.setStockQuantity((int) stockQuantity);
            product.setCategoryId(getCategoryIdByName(getCellValue(cell5)));
            product.setBrand(getCellValue(cell6));
            product.setSize((int) size);
            product.setImageUrl(getCellValue(cell8));
            products.add(product);
        }
        productMapper.insert(products);

        wb.close();//关闭文件
    }
    public Integer getCategoryIdByName(String categoryName) {
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Category::getCategoryName, categoryName);
        Category category = categoryMapper.selectOne(lambdaQueryWrapper);
        return category != null ? category.getId() : null;
    }


    @Transactional//查找商品
    public Result product(){
        return Result.success(productService.lambdaQuery().list());
    }
    @Transactional
    public Result order(){
        return Result.success(orderService.lambdaQuery().list());
    }

    @Transactional
    public Result userDetailInfo(){
        return Result.success(detailInfoService.lambdaQuery().list());
    }
    @Transactional
    public Result shipInfo(){
        return Result.success(shippingInformationService.lambdaQuery().list());
    }
    @Transactional
    public Result adminLogin(Map admin){
        String account = (String) admin.get("account");
        String password = (String) admin.get("password");
        Admin adminDb = adminService.lambdaQuery().eq(Admin::getAccount, account).one();
        String token = "";
        if (adminDb == null){
            return Result.fail(401,"管理员不存在");
        }
        if (Md5Util.passwordIsTrue(password, adminDb.getPassword())){
            token = JwtUtil.genToken(adminDb.getId());
            String tokenKey = "token:" + token;
            redisTemplate.opsForValue().set(tokenKey, token,168, TimeUnit.HOURS);
        } else {
            return Result.fail(400, "密码错误");
        }
        return Result.success(token);
    }
    @Transactional
    public Result<Admin> adminregister(Admin admin){
        Admin adminDb = adminService.lambdaQuery().eq(Admin::getAccount, admin.getAccount()).one();
        if (adminDb == null) {
            String md5 = Md5Util.getMD5(admin.getPassword());
            admin.setAccount(admin.getAccount());
            admin.setPassword(md5);
            adminService.save(admin);
            return Result.success(null);
        } else {
            return Result.fail(400, "注册失败，管理员已存在");
        }
    }
    @Transactional
    public Result DeleteProduct(Product product){
        boolean b = productService.removeById(product.getId());
        if (!b){
            return Result.fail(400,"删除商品失败");
        }
        return Result.success("删除商品成功");
    }
}
